import { echarts } from "@/config/echartsConfig"
import { debounce } from "lodash"

// 扩展 HTMLElement 类型，添加 _resizeChart 和 _chartInstance 属性
interface EChartsHTMLElement extends HTMLElement {
  _resizeChart?: () => void
  _chartInstance?: echarts.ECharts
}

export default {
  name: "chartResize", // 指令名称
  mounted(el: EChartsHTMLElement) {
    const chart = echarts.init(el)

    const resizeChart = debounce(() => {
      chart.resize()
    }, 200)

    window.addEventListener("resize", resizeChart)

    // 在元素卸载时移除监听器
    el._resizeChart = resizeChart
    el._chartInstance = chart
  },
  unmounted(el: EChartsHTMLElement) {
    // 移除窗口大小变化监听器
    if (el._resizeChart) {
      window.removeEventListener("resize", el._resizeChart)
    }
    if (el._chartInstance) {
      el._chartInstance.dispose()
    }
  }
}
